package com.hm.common.sqlite;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class SQLiteConn implements Serializable {
	private static final long serialVersionUID = 102400L;
	private static SQLiteConn sqLiteConn;

	@Value("${jdbc.sqlite.url}")
	private String dbfile;

	private SQLiteConn() {
	}

	public static SQLiteConn getInstance() {
		synchronized (SQLiteConn.class) {
			if (sqLiteConn == null) {
				sqLiteConn = new SQLiteConn();
			}
		}
		return sqLiteConn;
	}

	/**
	 * 与SQLite嵌入式数据库建立连接
	 * @return Connection
	 * @throws Exception
	 */
	public Connection getConnection() throws Exception {
		Connection connection = null ;
		try{
			Class.forName("org.sqlite.JDBC", true, this.getClass().getClassLoader()) ;
			connection = DriverManager.getConnection("jdbc:sqlite:" + dbfile);
		}catch (Exception e) {
			throw new Exception("" + e.getLocalizedMessage(), new Throwable("可能由于数据库文件受到非法修改或删除。")) ;
		}
		return connection;
	}
}
